package com.yuchen.bearrecord.config;

import com.yuchen.bearrecord.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class RequestHeaderContextInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        initHeaderContext(request);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    private void initHeaderContext(HttpServletRequest request) {

        String openid = request.getHeader("X-WX-OPENID");
        String appid = request.getHeader("X-WX-APPID");

        if (openid != null && appid != null) {
            log.info("openid >>> " + openid);
            log.info("appid >>> " + appid);
            new RequestHeaderContext.RequestHeaderContextBuild()
                    .UserDto(new UserDto(openid, appid))
                    .bulid();
        } else {
            log.info("HEADERS ERROR !!!");
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

}
